﻿using System.IO;

namespace Yzq.AudioConvert.Utilities
{
    public static class BytesToWav
    {
        public static byte[] ConvertBytesToWav(byte[] audioData, int channels, int sampleRate)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                using (BinaryWriter writer = new BinaryWriter(stream))
                {
                    WriteHeader(writer, audioData.Length, channels, sampleRate);
                    writer.Write(audioData);
                    return stream.ToArray();
                }
            }
        }
        private static void WriteHeader(BinaryWriter writer, int audioDataSize, int channels, int sampleRate)
        {
            writer.Write(System.Text.Encoding.UTF8.GetBytes("RIFF"));
            writer.Write(36 + audioDataSize);
            writer.Write(System.Text.Encoding.UTF8.GetBytes("WAVE"));
            writer.Write(System.Text.Encoding.UTF8.GetBytes("fmt "));
            writer.Write(16);
            writer.Write((ushort)1);
            writer.Write((ushort)channels);
            writer.Write(sampleRate);
            writer.Write(sampleRate * channels * 2); // byte rate
            writer.Write((ushort)(channels * 2)); // block align
            writer.Write((ushort)16); // bits per sample
            writer.Write(System.Text.Encoding.UTF8.GetBytes("data"));
            writer.Write(audioDataSize);
        }
    }
}